'use strict';

const BaseService = require('./base');
const modelName = 'Message';
const { Op } = require('sequelize');

class RouterService extends BaseService {
    constructor(ctx) {
        super(ctx, modelName);
    }
    pageOrder() {
        return [['create_time', 'DESC']]
    }

    getPage(where, page, pageSize, include) {
        return this.ctx.model[this.modelName].findAndCountAll({
            where,
            offset: pageSize * (page - 1),
            limit: pageSize,
            order: this.pageOrder() || [],
            include
        });
    }

    // 根据最后一条消息ID获取之前的消息
    async getMessagesByLastId(conversationId, lastMessageId, pageSize) {
        const where = {
            conversation_id: conversationId
        };

        // 如果有lastMessageId，添加id条件
        if (lastMessageId) {
            where.id = {
                [Op.lt]: lastMessageId // 获取ID小于lastMessageId的消息
            };
        }

        const result = await this.ctx.model[this.modelName].findAndCountAll({
            where,
            limit: pageSize,
            order: this.pageOrder(),
            raw: true
        });

        return {
            rows: result.rows,
            count: result.count
        };
    }
}

module.exports = RouterService;
